package com.spc.car.web.log.module;

import com.spc.car.common.utils.spring.SpringUtils;
import com.spc.car.core.framework.web.domain.AjaxResult;
import com.spc.car.data.entity.log.LogProjectOperation;
import com.spc.car.data.entity.project.Project;
import com.spc.car.data.service.project.ProjectService;
import com.spc.car.web.log.ProjectAction;
import com.spc.car.web.log.annotation.LogProjectAction;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.Objects;

public class LogProject extends BaseLogModule<LogProjectOperation, LogProjectAction> {
    public ProjectService projectService;

    public LogProject() {
        this.projectService = SpringUtils.getBean(ProjectService.class);
    }

    public LogProjectOperation toLogRecord(LogProjectAction logProjectAction,
                                           Map<String, Object> paramsMap,
                                           AjaxResult result) {
        LogProjectOperation logProjectOperation = new LogProjectOperation();
        if (Objects.isNull(this.projectService)) {
            return  logProjectOperation;
        }

        ProjectAction[] projectActions = logProjectAction.action();
        Project project = null;
        if (StringUtils.isNotBlank(logProjectAction.idForPost())
                && Objects.nonNull(paramsMap.get(logProjectAction.idForPost()))) {
            project = projectService.getById((Long)paramsMap.get(logProjectAction.idForPost()));
        }

        for (ProjectAction projectAction: projectActions) {
            if (projectAction.equals(ProjectAction.ADD)
                    && null == project
                    && StringUtils.isNotBlank(logProjectAction.idForReturn())
                    && Objects.nonNull(result.getByKey(logProjectAction.idForReturn()))) {
                Object idObj = result.getByKey(logProjectAction.idForReturn());
                if (idObj instanceof String) {
                    logProjectOperation.setProjectCode((String) idObj);
                    logProjectOperation.setRemark(projectAction.getName()
                            + "[" + paramsMap.get("name") + "]");
                    break;
                }
            } else if (projectAction.equals(ProjectAction.UPDATE) && null != project) {
                logProjectOperation.setProjectCode(project.getProjectCode());
                logProjectOperation.setRemark(projectAction.getName()
                        + "[" + paramsMap.get("name") + "]");
                break;
            }
        }
        return logProjectOperation;
    }
}
